<template>
  <TresGroup>
    <!-- 动态光效网格 -->
    <TresMesh ref="light" :rotation="[-Math.PI / 2, 0, 0]">
      <TresPlaneGeometry :args="[80, 80]" />
      <!-- <LightSweepMaterial /> -->
    </TresMesh>

    <!-- 网格线 -->
    <TresInstancedMesh
      ref="gridMesh"
      :args="[null, null, number * 2]"
      :position="[0, -0.01, 0]"
      :scale="2"
    >
      <TresPlaneGeometry :args="[lineWidth, baseHeight]" attach="geometry" />
      <TresMeshBasicMaterial color="#999" attach="material" />
    </TresInstancedMesh>
  </TresGroup>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useTres } from "@tresjs/core"; // 保留 useTres 从 core 导入
// import { useFrame } from "@tresjs/cientos"; // 从 cientos 导入 useFrame
import { Matrix4 } from "three";
import { Text3D } from "@tresjs/cientos";
import "../shader/lightSweep.js";

const props = defineProps({
  baseHeight: {
    type: Number,
    required: true,
  },
  values: {
    type: Object,
    required: true,
  },
});

// 网格配置
const number = 23;
const lineWidth = 0.026;
const T = Math.PI / 2;

// 引用和状态
const light = ref(null);
const gridMesh = ref(null);
const gridArray = computed(() => Array.from({ length: number }));

// 文本配置
const textConfig = {
  curveSegments: 32,
  bevelEnabled: true,
  bevelSize: 0,
  bevelThickness: 0,
  height: 0.02,
  letterSpacing: 0,
  size: 0.6,
};

// 使用 useTres 获取场景状态
const { clock } = useTres();

// 动画帧处理函数
const animate = (time) => {
  const elapsedTime = time / 3;
  const stage = (elapsedTime / T) % 2;

  if (light.value && light.value.material && light.value.material.uniforms) {
    if (stage < 1) {
      light.value.material.uniforms.innerRadius.value =
        1.5 * Math.abs(Math.sin(elapsedTime));
    } else {
      light.value.material.uniforms.innerRadius.value = 0;
    }
  }
};

// 生命周期钩子
onMounted(() => {
  // 设置网格实例
  if (gridMesh.value && gridMesh.value.instance) {
    const instance = gridMesh.value.instance;
    const matrix = new Matrix4();
    let index = 0;

    for (let y = 0; y < number; y++) {
      for (let x = 0; x < number; x++) {
        // 计算位置
        const posX = x * 2 - Math.floor(number / 2) * 2;
        const posZ = y * 2 - Math.floor(number / 2) * 2;

        // 设置水平和垂直网格线
        matrix.setPosition(posX, -0.01, posZ);
        instance.setMatrixAt(index++, matrix);

        matrix.setPosition(posX, -0.01, posZ);
        matrix.rotateY(Math.PI / 2);
        instance.setMatrixAt(index++, matrix);
      }
    }

    instance.instanceMatrix.needsUpdate = true;
  }

  // 使用 useFrame 处理动画
  // useFrame((state) => {
  //   if (clock) {
  //     animate(state.clock.getElapsedTime());
  //   }
  // });
});
</script>
